package com.example.qt.ptplatform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.qt.ptplatform.entity.CommentFavorite;
import com.example.qt.ptplatform.entity.vo.CommentFavoriteVO;
import com.example.qt.ptplatform.mapper.CommentFavoriteMapper;
import com.example.qt.ptplatform.service.CommentFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class CommentFavoriteServiceImpl implements CommentFavoriteService {

    @Autowired
    private CommentFavoriteMapper commentFavoriteMapper;

    @Override
    @Transactional
    public boolean favoriteComment(Integer userId, Integer commentId) {
        if (userId == null || commentId == null) {
            return false;
        }

        // 检查是否已收藏
        if (isFavorite(userId, commentId)) {
            return false;
        }

        CommentFavorite favorite = new CommentFavorite();
        favorite.setUserId(userId);
        favorite.setCommentId(commentId);
        favorite.setCreateTime(LocalDateTime.now());

        return commentFavoriteMapper.insert(favorite) > 0;
    }

    @Override
    @Transactional
    public boolean unfavoriteComment(Integer userId, Integer commentId) {
        if (userId == null || commentId == null) {
            return false;
        }

        LambdaQueryWrapper<CommentFavorite> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CommentFavorite::getUserId, userId)
                .eq(CommentFavorite::getCommentId, commentId);

        return commentFavoriteMapper.delete(wrapper) > 0;
    }

    @Override
    public boolean isFavorite(Integer userId, Integer commentId) {
        if (userId == null || commentId == null) {
            return false;
        }
        return commentFavoriteMapper.existsByUserAndComment(userId, commentId) > 0;
    }

    @Override
    public int getFavoriteCountByUser(Integer userId) {
        if (userId == null) {
            return 0;
        }
        return commentFavoriteMapper.countByUserId(userId);
    }

    @Override
    public List<CommentFavoriteVO> getUserFavoriteComments(Integer userId) {
        if (userId == null) {
            return Collections.emptyList();
        }
        return commentFavoriteMapper.selectFavoriteCommentsByUserId(userId);
    }
}